package com.erlang.springmvc.service.impl;

import com.erlang.springmvc.pojo.FileObject;
import com.erlang.springmvc.service.FileObjectService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @Description： 文件上传服务实现类
 */
@Service
public class FileObjectServiceImpl implements FileObjectService {


    @Override
    public FileObject upLoad(MultipartFile multipartFile, Integer businessId, String businessType) {
        //构建文件对象
        FileObject fileObject =new FileObject();
        if (multipartFile==null){
            return null;
        }
        //关联业务
        fileObject.setBusinessId(businessId);
        fileObject.setBusinessType(businessType);
        String originalFilename = multipartFile.getOriginalFilename();
        //获得后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //构建新文件名称
        String fileName = UUID.randomUUID().toString();
        //构建访问路径
        String pathUrl = businessType+"/"+fileName+suffix;
        //判定文件夹是否创建
        File file = new File("D:/virtual/file-service/"+businessType);
        if (!file.exists()){
            file.mkdir();
        }
        //绑定请求路径
        fileObject.setPathUrl(pathUrl);
        //构建上传文件
        file = new File("D:/virtual/file-service/" + pathUrl);
        try {
            //文件上传
            multipartFile.transferTo(file);
            fileObject.setCreateTime(new Date());
            System.out.println("文件上传成功！");
            return fileObject;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件上传失败！");
        }
        return fileObject;
    }
}